package com.toutiao.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.base.action.CoreController;
import com.base.dao.model.Ret;
import com.base.dialect.PaginationSupport;
import com.base.util.JSONUtils;
import com.base.web.annotation.LoginFilter;
import com.toutiao.dao.model.News;
import com.toutiao.daoEx.model.NewsEx;
import com.toutiao.service.NewsService;

@RequestMapping("news")
@Controller
@LoginFilter
public class NewsController extends CoreController{

	@Autowired
	private NewsService newsService;

	@RequestMapping("/list")
	@ResponseBody
	public String list(Integer page, Integer rows, String name){
		PaginationSupport.byPage(page, rows);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("name", name);
		List<NewsEx> list = newsService.selectList(map);
		return page(list);
	}

	@RequestMapping("/save")
	@ResponseBody
	public String save(News news){
		if(null != news.getType() && news.getType() != 3 ){
			JSONArray arr = JSONArray.parseArray(news.getContent());
			if (arr != null) {
				List<String> imgs = new ArrayList<>(3);
				for (int i = 0; i < arr.size(); i++) {
					JSONObject mini = arr.getJSONObject(i);
					if (imgs.size() < 3) {
						if (StringUtils.isNotBlank(mini.getString("img"))){
							imgs.add(mini.getString("img"));
						}
					}else{
						break;
					}
				}
				news.setImgs(StringUtils.join(imgs, ","));
			}
		}
		if (news.getId() == null){			
			news.setUserId(0);
			newsService.insert(news);
		}else{
			newsService.updateByPrimaryKeySelective(news);
		}
		return JSONUtils.serialize(new Ret(0));
	}

	@RequestMapping("/findById")
	@ResponseBody
	public String find(Integer id){
		News news = newsService.selectByPrimaryKey(id);
		return JSONUtils.serialize(news);
	}
	
	@RequestMapping("/del")
	@ResponseBody
	public String del(String id){
		String[] ids = id.split(",");
		for (String str : ids){
			newsService.updateByPrimaryKeys(Integer.parseInt(str));
		}
		return JSONUtils.serialize(new Ret(0));
	}

}